package com.jiyang.jyandroid.test06;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

import com.jiyang.jyandroid.BaseActivity;

/**
 * Created by jy on 2016/12/2.
 * 手机电量提示
 */

public class Six_2Activity extends BaseActivity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Button button = new Button(this);
        button.setText("点击显示当前电量");
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MyBroadcastReceiver myBroadcastReceiver = new MyBroadcastReceiver();
                IntentFilter filter = new IntentFilter();
                filter.addAction(Intent.ACTION_BATTERY_CHANGED);
                registerReceiver(myBroadcastReceiver, filter);
            }
        });
        addContentView(button, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
    }

    private class MyBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Intent.ACTION_BATTERY_CHANGED)) {
                Bundle bundle = intent.getExtras();
                int current = bundle.getInt("level");
                Toast.makeText(Six_2Activity.this, "当前电量:" + String.valueOf(current), Toast.LENGTH_SHORT).show();
            }
        }
    }
}
